package com.example.demo.commen;

import org.apache.tomcat.util.digester.Digester;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * user:likai
 * Date:2023-03-04
 * Time:15:51
 */
//加盐加密
public class SecurityUtil {
    public static String encrypt(String password){
        //设置固定长度为32位的盐
        String salt= UUID.randomUUID().toString().replace("-","");
        //最终密码
        String finalPassword= DigestUtils.md5DigestAsHex((salt+password).getBytes());
        return salt+finalPassword;
    }
    //解密
    //password待验证的密码
    public static boolean decrypt(String password,String finalPassword){
        //非空校验
        if(!StringUtils.hasLength(password)||!StringUtils.hasLength(finalPassword)){
            return false;
        }
        if(finalPassword.length()!=64){
            return false;
        }
        String salt=finalPassword.substring(0,32);
        String security=DigestUtils.md5DigestAsHex((salt+password).getBytes());
        return (salt+security).equals(finalPassword);
    }
}
